<template>
	<el-card>
		<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
			<el-form-item>
				<el-input v-model="state.queryForm.sysObjectName" placeholder="附件名称"></el-input>
			</el-form-item>
			<el-form-item>
				<el-input v-model="state.queryForm.sysObjectPath" placeholder="文件路径"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button @click="getDataList()">查询</el-button>
			</el-form-item>
			<el-form-item v-auth="'sys:attachment:save'">
				<el-upload :action="constant.uploadUrl" :before-upload="beforeUpload" :on-success="handleSuccess" :show-file-list="false">
					<el-button type="primary">上传</el-button>
				</el-upload>
			</el-form-item>
			<el-form-item>
				<el-button v-auth="'sys:attachment:delete'" type="danger" @click="deleteList()">删除</el-button>
			</el-form-item>
		</el-form>
		<el-table :data="state.dataList" border style="width: 100%" @selection-change="selectionChangeHandle">
			<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
			<el-table-column prop="sysObjectName" label="附件名称" show-overflow-tooltip header-align="center" align="center"></el-table-column>
			<el-table-column prop="sysObjectPath" label="附件地址" show-overflow-tooltip header-align="center" align="center"></el-table-column>
			<el-table-column prop="sysObjectPath" label="附件预览" show-overflow-tooltip header-align="center" align="center">
				<template #default="scope">
					<img
						:src="def + 'sys/object/readFile?accessToken=' + cache.getToken() + '&filePath=' + scope.row.sysObjectPath"
						style="width: 100px; height: 100px"
					/>
				</template>
			</el-table-column>
			<el-table-column prop="sysObjectSize" label="附件大小" header-align="center" align="center">
				<template #default="scope">
					{{ convertSizeFormat(scope.row.sysObjectSize) }}
				</template>
			</el-table-column>
			<el-table-column prop="sysOrgId" label="存储平台" header-align="center" align="center"></el-table-column>
			<el-table-column prop="createTime" label="创建时间" header-align="center" align="center"></el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="200">
				<template #default="scope">
					<el-button type="primary" link @click="downloadHandle(scope.row.sysObjectPath, scope.row.sysObjectName)"> 下载 </el-button>

					<!-- Form -->
					<el-button type="primary" link @click="edit(scope.row)">编辑</el-button>
					<el-dialog v-model="dialogFormVisible" title="请输入编辑内容" :modal="false">
						<generate-form ref="generateFormRef" :data="widgetForm"></generate-form>
						<template #footer>
							<span class="dialog-footer">
								<el-button @click="dialogFormVisible = false">取消</el-button>
								<el-button type="primary" @click="handleSubmit(scope.row)"> 提交</el-button>
							</span>
						</template>
					</el-dialog>

					<el-button v-auth="'sys:attachment:delete'" type="primary" link @click="deleteList(scope.row.sysObjectId,scope.row.sysObjectPath)"> 删除 </el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.page"
			:page-sizes="state.pageSizes"
			:page-size="state.limit"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>
	</el-card>
</template>

<script setup lang="ts" name="SysAttachmentIndex">
import { useCrud } from '@/hooks'
import { reactive, ref } from 'vue'
import constant from '@/utils/constant'
import { convertSizeFormat } from '@/utils/tool'
import { IHooksOptions } from '@/hooks/interface'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { useAttachmentSubmitApi } from '@/api/sys/attachment'
import cache from '@/utils/cache'
import service from '@/utils/request'

const state: IHooksOptions = reactive({
	dataListUrl: '/sys/object/queryPage',
	deleteUrl: '/sys/object/listDelete',
	queryForm: {
		sysObjectId: '',
		sysObjectName: '',
		sysObjectPath: '',
		sysOrgId: '',
		sysObjectSize: '',
		updater: ''
	}
})
const dataForm = reactive({
	sysObjectId: '',
	sysObjectName: '',
	sysObjectPath: '',
	sysOrgId: '',
	sysObjectSize: '',
	updater: ''
})
const url = import.meta.env.VITE_API_URL
const def = ref(url)
//图片返回参数结构体
const fileStructure = reactive({
	filePath: '',
	fileName: '',
	fileSize: 0,
	fileContentType: ''
})
const handleSuccess: UploadProps['onSuccess'] = (res, file) => {
	console.log('打印上传以后的信息' + JSON.stringify(res))
	fileStructure.fileName = res.data.fileName
	fileStructure.filePath = res.data.filePath
	fileStructure.fileContentType = res.data.fileContentType
	fileStructure.fileSize = res.data.fileSize
	if (res.code !== 0) {
		ElMessage.error('上传失败：' + res.msg)
		return false
	}

	Object.assign(dataForm, res.data)

	//上传
	//重构
	const upload = {
		sysObjectPath: fileStructure.filePath,
		sysObjectName: fileStructure.fileName,
		sysObjectSize: fileStructure.fileSize
	}
	useAttachmentSubmitApi(upload).then(() => {
		console.log('传入的参数' + JSON.stringify(undefined))
		ElMessage.success({
			message: '上传成功',
			duration: 500,
			onClose: () => {
				getDataList()
			}
		})
	})
}
const beforeUpload: UploadProps['beforeUpload'] = file => {
	if (file.size / 1024 / 1024 / 1024 / 1024 > 1) {
		ElMessage.error('文件大小不能超过100M')
		return false
	}
	return true
}
const { getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle, deleteBatchHandle, downloadHandle } = useCrud(state)

//编辑
const dialogFormVisible = ref(false)

//编辑表单设计
const generateFormRef = ref()
const edit = (row: any) => {
	dialogFormVisible.value = true
	console.log('编辑的函数' + JSON.stringify(row))
}
let widgetForm = {
	list: [
		{
			type: 'grid',
			label: '格栅布局',
			columns: [
				{
					span: 15,
					list: [
						{
							type: 'input',
							label: '附件标题：',
							options: {
								defaultValue: dataForm.sysObjectName,
								maxlength: 32,
								placeholder: 'title',
								labelHide: false,
								disabled: false,
								readonly: false,
								clearable: false,
								showPassword: false,
								showWordLimit: false,
								rules: []
							},
							key: 'vk02yvgy',
							name: 'sysObjectName'
						}
					]
				},
				{
					span: 15,
					list: [
						{
							type: 'input',
							label: '附件地址：',
							options: {
								defaultValue: '',
								maxlength: 32,
								placeholder: '/src',
								labelHide: false,
								disabled: false,
								readonly: false,
								clearable: false,
								showPassword: false,
								showWordLimit: false,
								rules: []
							},
							key: 'fw1kssxb',
							name: 'sysObjectPath'
						}
					]
				},
				{
					span: 15,
					list: [
						{
							type: 'input',
							label: '平台地址：',
							options: {
								defaultValue: '',
								maxlength: 32,
								placeholder: 'platform',
								labelHide: false,
								disabled: false,
								readonly: false,
								clearable: false,
								showPassword: false,
								showWordLimit: false,
								rules: []
							},
							key: 'dxdebgb1',
							name: 'sysOrgId'
						}
					]
				}
			],
			options: { gutter: 0, justify: 'center', align: 'top' },
			key: '6ycl80kn',
			name: 'grid_ampkud'
		}
	],
	config: { size: 'default', labelWidth: 100, labelPosition: 'right', style: '' }
}

const handleSubmit = (row: any) => {
	dialogFormVisible.value = false
	generateFormRef.value
		.getData()
		.then((data: any) => {
			//{"title":"xxx","src":"xxx","plat":"xxx"}data...
			///{sys/object}/listUpdate
			data.sysObjectId = row.sysObjectId
			console.log(JSON.stringify(data) + 'data...')
			let array = [data]
			service.post('sys/object/listUpdate', array).then(res => {
				console.log('已经发送数据')
			})
		})
		.catch((error: any) => {
			// data failed
		})
}

// 删除
const deleteList = (key?: number | string,path?:any) => {
	let data: any[] = []
	if (key) {
		data = [{ sysObjectId: key ,sysObjectPath:path  }]
	} else {
		data = state.dataListSelections ? state.dataListSelections : []

		if (data.length === 0) {
			ElMessage.warning('请选择删除记录')
			return
		}
	}

	ElMessageBox.confirm('确定进行删除操作?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			if (state.deleteUrl) {
				// console.log('打印删除地址{}', state.deleteUrl)
				// console.log('打印删除参数', data)
				service.delete(state.deleteUrl, { data }).then(() => {
				  ElMessage.success('删除成功')
				  getDataList()
				})
			}
		})
		.catch(() => {})
}
</script>
<style scoped>
.el-button--text {
	margin-right: 15px;
}

.el-select {
	width: 300px;
}

.el-input {
	width: 300px;
}

.dialog-footer button:first-child {
	margin-right: 10px;
}
</style>
